//
//  RequestGenerator.swift
//  Asman
//
//  Created by 李旭峰 on 5/16/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import Foundation
import Alamofire

let kTimeOut: TimeInterval = 60

let kMessageEncryption = "app_2017"

let kMyBoundary = "myboundary"

let kID = "exchange_search_id"

class RequestGenerator {
    static func generateReuqest(_ serviceIdentifier: Service,
                                baseUrl:String?,
                                httpMethod: HTTPMethodType,
                                methodName: String,
                                timeoutInterval:TimeInterval=kTimeOut,
                                mock:String? = nil,
                                customerHeader:[String:Any]? = nil,
                                query:[String:Any]? = nil,
                                body:Any? = nil) -> URLRequest
    {
        let server = ServerFactory.default.server(identifier: serviceIdentifier)
        var validBaseUrl = server.baseurl
        if let customBaseUrl = baseUrl,customBaseUrl.count >= 1 {
            validBaseUrl = customBaseUrl
        }
        if let tempMock = mock,tempMock.count >= 1 {
            validBaseUrl += tempMock
        }
        validBaseUrl += methodName
        if let tempQuery = query {
            validBaseUrl = self.mergeParams(tempQuery, urlString: validBaseUrl)
        }
        let url = URL(string: validBaseUrl.analyseCnString())!
        var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeoutInterval)
        if httpMethod == .upload {
            request.httpMethod = "POST"
        }else {
            request.httpMethod = httpMethod.rawValue
        }
        if httpMethod != .get, let tempBody = body {
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: tempBody, options: [.fragmentsAllowed])
            } catch {
                dPrintServerError("请求编码错误")
            }
        }
        let infoDictionary = Bundle.main.infoDictionary
        let majorVersion:String = String.SwitchToString(infoDictionary?["CFBundleShortVersionString"]) ?? ""
        request.setValue(majorVersion, forHTTPHeaderField: "x-application-version")
        request.setValue("12", forHTTPHeaderField: "x-application-type")
//        request.setValue(PageConfigTool.Server_domainPrefix(), forHTTPHeaderField: "x-tenant-prefix")
        request.setValue("ios", forHTTPHeaderField: "x-application-os")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if let tempCustomerHeader = customerHeader {
            for (key,value) in tempCustomerHeader {
                request.setValue(String.SwitchToString(value), forHTTPHeaderField: key)
            }
        }
        return request
    }
    static private func mergeParams(_ params:[String:Any],urlString:String) -> String {
        if params.count <= 0 {
            return urlString
        }
        var resultUrlStr = urlString
        if !resultUrlStr.contains("?") {
            resultUrlStr += "?"
        }
        var index = 0
        for (key,value) in params {
            index += 1
            if let tempValue = value as? CustomStringConvertible {
                resultUrlStr += (key + "=" + tempValue.description)
            }
            if index < params.count {
                resultUrlStr += "&"
            }
        }
        return resultUrlStr
    }
    
    
    class func signParams(_ params:[String: Any]) -> String {
        let filterDict = params.filter {
            if $0.1 is String {
                return ($0.1 as! String).count > 0
            }
            return true
        }
        let sortDict = filterDict.sorted {  $0.0 < $1.0 }
        
        var sortStr = sortDict.reduce("", {
            return $0 + $1.0 + "=\($1.1)" + "&"
        })
        sortStr.removeLast()
        dPrintServerSend(sortStr)
        let md5 = sortStr.md5
        return md5
    }
    
}
